<?php

namespace app\model;

use ali\Sms;
use payment\Hpay;
use think\facade\Cache;
use think\helper\Str;
use think\Model;
use think\model\relation\HasOne;

class Order extends Model
{
    public function productData(): HasOne
    {
        return $this->hasOne(Product::class, "id", "product");
    }

    public function gift(): HasOne
    {
        return $this->hasOne(Package::class, "id", "gid");
    }

    public function attrData(): HasOne
    {
        return $this->hasOne(PackageAttr::class, "id", "attr");
    }

    public function codeData(): HasOne
    {
        return $this->hasOne(PlateformCode::class, "code", "code");
    }

    public function lst(): array
    {
        $param = request()->param();
        $data = $this->with(['productData', 'gift', 'attrData'])->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->where('mobile', $param['mobile']);
        })->order(['product' => 'asc', 'create_time' => 'desc'])->paginate(['list_rows' => 15, 'page' => $param['page'] ?? 1])->toArray();
        return ['lst' => $data['data'], 'lastPage' => $data['last_page']];
    }

    public function pageData(): array
    {
        $param = request()->param();
        $data = $this->with(['productData', 'gift', 'attrData', 'codeData' => function ($query) {
            $query->with(['plate']);
        }])->when(!empty($param['mobile']), function ($query) use ($param) {
            $query->where('mobile', $param['mobile']);
        })->when(!empty($param['order']), function ($query) use ($param) {
            $query->where('order_sn', $param['order']);
        })->when(!empty($param['state']), function ($query) use ($param) {
            $query->whereIn('state', $param['state']);
        })->order('create_time', 'desc')->paginate([
            "list_rows" => $param['pageSize'] ?? 15,
            "page" => $param['page'] ?? 1
        ])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total']];
    }

    public function checkMobile(): array
    {
        $mobile = request()->param("mobile");
        if (Cache::get("check_sms_$mobile")) throw new \Exception("请勿重复发送", 743018);
        $timer = Cache::get("sms_{$mobile}_code_" . date("Ymd"), 0);
        if ($timer > 5) throw new \Exception("短信发送次数过多", 743017);
        $count = $this->where(['mobile' => $mobile])->count();
        if ($count < 1) throw new \Exception("该手机号未购买过礼包", 743019);
        $code = Str::random(6, 1);
        $send = Sms::sendSms($mobile, ["code" => $code], "SMS_474460088");
//        dd($send);
        if (empty($send) || strtolower($send['Code']) != "ok") throw new \Exception($send["Message"] ?? "短信发送失败", 743020);
        Cache::set("sms_{$mobile}_code", $code, 300);
        Cache::set("check_sms_{$mobile}", 1, 60);
        $timer++;
        Cache::set("sms_{$mobile}_code_" . date("Ymd"), $timer, 24 * 3600);
        return $send;
    }

    public function detail()
    {
        $param = request()->param();
        $data = $this->with(['productData', 'gift', 'attrData'])->when(!empty($param['id']), function ($query) use ($param) {
            $query->where('id', '=', $param['id']);
        })->when(!empty($param['order']), function ($query) use ($param) {
            $query->where('order_sn', '=', $param['order']);
        })->find();
        $data->productData->content = htmlspecialchars_decode($data->productData->content);
        return $data->toArray();
    }

    public function payment()
    {
        $param = request()->post();
        $order_sn = date("YmdHis") . Str::random(4, 1);
        $this->startTrans();
        $order = array_map(function ($v) use ($order_sn, $param) {
            return [
                "order_sn" => $order_sn,
                "mobile" => $param['mobile'],
                "account" => $param['mobile'],
                "gid" => $param['pack'],
                "attr" => $param['attr'],
                "code" => 'sys' . Str::random(4, 1),
                'number' => $v['number'],
                'state' => 1,
                "price" => $v['money'],
                "product" => $v['id']
            ];
        }, $param['product']);
        //获取礼包价值
        $gift = Package::findOrFail($param['pack']);
        $this->saveAll($order);
        //生成支付订单
        $pay = app(Hpay::class)->createPayOrder([
            "outTradeNo" => $order_sn,
            "transType" => "JSAPI",
            "payMode" => "WECHAT",
            "totalAmount" => $gift->price,
            "profitSharing" => "0",
            "subject" => $gift->name,
            "userId" => $param['openid'],
            "notifyUrl" => request()->domain() . "/wechat/pay_notify",
        ]);
        if ($pay['code'] != 0) throw new \Exception($pay['message'], 70985);
        $this->commit();
        $this->where(['order_sn' => $order_sn])->update([
            "paid" => $pay['data']['payParam']['package']
        ]);
        return $pay['data'];
    }
}
